/**
 * 通用 js
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 *
 * @version 1.0 2016-10-25 。
 * ============================================================================
 */

/* ajax 封装 */
/*======================================*/
// 异步 load content 页面
function loadURL(url, ajax_container) {
    $.ajax({
        type : 'GET',
        url : url,
        dataType : 'html',
        contentType: 'application/x-www-form-urlencoded; charset=utf-8',
        cache : false, // (warning: this will cause a timestamp and will call the request twice)
        async : true,
        beforeSend : function() {
            // loading
            var loadPage =
                '<div class="page-content">'+
                '<div class="cls-container">'+
                '<div class="cls-content">'+
                '<div class="spiner-example">'+
                '<div class="sk-spinner sk-spinner-three-bounce">'+
                '<div class="sk-bounce1"></div>'+
                '<div class="sk-bounce2"></div>'+
                '<div class="sk-bounce3"></div>'+
                '</div>'+
                '</div>'+
                '</div>'+
                '</div>'+
                '</div>';
            ajax_container.html(loadPage);

            // only draw breadcrumb if it is content material
            // TODO: check if document title injection refreshes in IE...
            // TODO: see the framerate for the animation in touch devices
            if (ajax_container[0] == $('#container')[0]) {
                // scroll up
                $('html, body').animate({
                    scrollTop : 0
                }, 'fast');
            } else {
                ajax_container.animate({
                    scrollTop : 0
                }, 'fast');
            }
        },
        complete: function(){
            // Handle the complete event
        },
        success : function(data) {
            // end loading...
            ajax_container.css({
                opacity : '0.0'
            }).html(data).delay(50).animate({
                opacity : '1.0'
            }, 300);

        },
        error : function(xhr, ajaxOptions, thrownError) {
            // error
            var errorPage =
                '<div id="page-content">'+
                '<div class="cls-container">'+
                '<div class="cls-content">'+
                '<h1 class="error-code text-info">404</h1>'+
                '<p class="text-main text-semibold text-lg text-uppercase">页面没有找到!</p>'+
                '<div class="pad-btm text-muted">'+
                '抱歉，你访问的页面地址有误，或者该页面不存在。'+
                '</div>'+
                '<div class="pad-top"><a class="btn-link" href="index">返回首页</a></div>'+
                '</div>'+
                '</div>'+
                '</div>';
            ajax_container.html(errorPage);
        }
    });
}

// 发送ajax请求
function __ajax_get(url, params, success, opt){
    var defaults = {
        cache: false,
        url: url,
        timeout : 300000,
        type:'GET',
        data: params,
        dataType: 'json',
        beforeSend: null,
        complete: null,
        success: function (data) {
            if(typeof success === 'function'){
                success(data, params);
            }
        },
        error: function (data) {
            if(typeof success === 'function'){
                success(data, params);
            }
        }
    };
    var options = $.extend({}, defaults, opt);

    $.ajax(options);
}

// 发送ajax请求
function __ajax_post(url, params, success, opt){

    var defaults = {
        cache: false,
        timeout : 300000,
        url: url,
        type:'POST',
        data: params,
        dataType: 'json',
        beforeSend: null,
        complete: null,
        success: function (data) {
            if(typeof success === 'function'){
                success(data, params);
            }
        },
        error: function (data) {
            alert('ddd')
            if(typeof success === 'function'){
                success(data, params);
            }
        }

    };
    var options = $.extend({}, defaults, opt);

    $.ajax(options);
}

// 保存方法
function __form_save(form_id, url, success, opt) {
    var defaults = {
        dialogId: null,
        showMessage: true
    };
    var options = $.extend({}, defaults, opt);

    $('#'+form_id+' input:disabled').removeAttr('disabled');
    var params = $('#'+form_id).serialize();
    __ajax_post(url, params, function(data, params){
        if(options.showMessage){
            __toastr(data);
        }
        if(typeof success === 'function'){
            var params_save = $.extend({}, params, {
                dialogId: options.dialogId
            });
            success(data, params_save);
        }

    });
}

//联动多选
function multList(ulId_first,ulId_second,actionUrl){
    $("ul#"+ulId_first+" input").each(function(index,value){
        $(this).on("change",function(event){
            var check = $(this).is(":checked");
            var data = {rowId:$(this).attr("id"),keyId:$("input#keyId").val()}
            $.ajax({
                url : actionUrl,
                method:"post",
                cache : false,
                dataType : "json",
                async : false,
                data : data,
                success : function(data) {
                    var data = eval(data.rows);
                    $(data).each(function(index,value){
                        var str = "<li class='list-group-item td-li' id="+value.id+">"+
                            "<div class='checkbox'>"+
                            "<label>"+
                            "<input id="+value.id+" type='checkbox' class='checkbox style-0' >"+
                            "<span id="+value.name+">"+value.name+"</span>"+
                            "</label>"+
                            "</div>"+
                            "</li>";
                        if(check == true){
                            $(str).appendTo("ul#"+ulId_second);
                        }else{
                            $("li#"+value.id).remove();
                        }

                    });
                }
            });
        })
    });
}


//ulId - 列表框ul的Id,获取dialog中选中的值
function getRowIds(ulId){
    var objChk = $("ul#"+ulId+" input:checked");
    var rowIds = [];
    if(objChk.length>0){
        $(objChk).each(function(index,value){
            var rowData = $(this).attr("id");
            rowIds.push({"id":rowData});
        });
    }
    var rowIds = JSON.stringify(rowIds);
    return rowIds;
}
/*======================================*/



/* toastr 封装 */
/*======================================*/

function __toastr_primary(title, message){
    $.niftyNoty({
        type: 'primary',
        container : "floating",
        title : title,
        message : message,
        closeBtn : true,
        timer : 3000
    });
}

function __toastr_success(message){
    $.niftyNoty({
        type: 'success',
        container : "floating",
       // title : '成功',
        message : message,
        closeBtn : true,
        timer : 3000
    });
}

function __toastr_info(message){
    $.niftyNoty({
        type: 'info',
        container : "floating",
        title : '消息',
        message : message,
        closeBtn : true,
        timer : 3000
    });
}

function __toastr_warning(message){
    $.niftyNoty({
        type: 'warning',
        container : "floating",
        title : '提示',
        message : message,
        closeBtn : true,
        timer : 5000
    });
}

function __toastr_error(message){
    $.niftyNoty({
        type: 'danger',
        container : "floating",
        title : '错误',
        message : message,
        closeBtn : true,
        timer : 5000
    });
}

function __toastr(data){
    if (data) {
        if(data.state == 1){
            __toastr_success(data.message);
        }else{
            __toastr_error(data.message);
        }
    }
}

/*======================================*/


/* dialog 封装 */
/*======================================*/

var Admin_Package_BootstrapDialog = function (dialog) {
    this.setDialog(dialog)
};

Admin_Package_BootstrapDialog.prototype = {
    getDialog: function () {
        return this.dialog;
    },
    setDialog: function (dialog) {
        this.dialog = dialog;

        return this;
    },
    id : function () {
        return this.getDialog().getId()
    },
    enableButtons : function () {
        this.getDialog().enableButtons(true);

        return this;
    },
    disenableButtons : function () {
        this.getDialog().enableButtons(false);

        return this;
    },
    close : function () {
        this.getDialog().close();

        return this;
    }
};

// 弹出框
function __open_dialog(size, title, url, buttons, opt) {
    var defaults = {
        size: size,
        title: title,
        message: function(dialog) {
            var $message = $('<div class="form-read"></div>');
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad);
            return $message;
        },
        data: {
            'pageToLoad': url
        },
        closable: false,
        buttons: buttons,
        draggable:true,
        resizable: true
    };

    var options = $.extend({}, defaults, opt);

    var dialog = BootstrapDialog.show(options);

     return new Admin_Package_BootstrapDialog(dialog);
}

// 提示框
function __alert_dialog(type, size, title, message, buttons, opt) {
    var defaults = {
        type: type,
        size: size,
        title: title,
        message: message,
        buttons: buttons
    };
    var options = $.extend({}, defaults, opt);

    var dialog = BootstrapDialog.show(options);
    return new Admin_Package_BootstrapDialog(dialog);
}

// 表单 dialog
function __open_dialog_form(title, url, confirm, opt) {
    var dialogRef = __open_dialog(BootstrapDialog.SIZE_WIDE, title, url,
        [{
            icon: 'ti-check',
            label: '保存',
            cssClass: 'btn-primary',
            action: function () {
                // 禁用按钮
                dialogRef.disenableButtons();
                // 执行方法
                if(typeof confirm === 'function'){
                    confirm(dialogRef);
                }
            }
        }, {
            icon: 'ti-close',
            label: '关闭',
            cssClass: 'btn-default',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
            }
        }],
        opt
    );
    return dialogRef;
}

// 只读表单 dialog
function __open_dialog_form_read(title, url, opt) {
    var dialogRef = __open_dialog(BootstrapDialog.SIZE_WIDE, title, url,
        [{
            icon: 'ti-close',
            label: '关闭',
            cssClass: 'btn-default',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
            }
        }],
        opt
    );
    return dialogRef;
}

// 选择框 dialog
function __open_dialog_select(title, url, confirm, opt) {
    var dialogRef =  __open_dialog(BootstrapDialog.SIZE_NORMAL, title, url,
        [{
            label: '确定',
            cssClass: 'btn-primary',
            action: function () {
                // 禁用按钮
                dialogRef.disenableButtons();
                // 执行方法
                if(typeof confirm === 'function'){
                    confirm(dialogRef);
                }
            }
        }, {
            label: '取消',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
            }
        }],
        opt
    );
    return dialogRef;
}

// 确认 提示框
function __confirm_dialog(title, message, confirm, cancel, opt) {
    var dialogRef = __alert_dialog(BootstrapDialog.TYPE_PRIMARY, BootstrapDialog.SIZE_SMALL, title, message,
        [{
            label: '取消',
            cssClass: 'btn-default',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
                // 执行方法
                if(typeof cancel === 'function'){
                    cancel(dialogRef);
                }
            }
        }, {
            label: '确定',
            cssClass: 'btn-primary',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
                // 执行方法
                if(typeof confirm === 'function'){
                    confirm(dialogRef);
                }
            }
        }],
        opt
    );
    return dialogRef;
}

// 确认 提示框
function __confirm_dialog_input(title, hint, value, confirm, cancel, opt) {
    var $input = $('<input type="text" class="form-control" value="'+value+'" placeholder="'+hint+'" autofocus>');

    var dialogRef = __alert_dialog(BootstrapDialog.TYPE_PRIMARY, BootstrapDialog.SIZE_SMALL, title,
        function () {
            var $message = $('<div class="form-group"></div>');
            $message.append($input);
            return $message;
        },
        [{
            label: '取消',
            cssClass: 'btn-default',
            action: function () {
                // 关闭 dialog
                dialogRef.close();
                // 执行方法
                if(typeof cancel === 'function'){
                    cancel(dialogRef);
                }
            }
        }, {
            label: '确定',
            cssClass: 'btn-primary',
            action: function () {
                // 禁用按钮
                dialogRef.disenableButtons();
                // 输入框
                var inputValue = $input.val();
                // 执行方法
                if(typeof confirm === 'function'){
                    confirm(dialogRef, inputValue);
                }
            }
        }],
        opt
    );
    return dialogRef;
}

/*======================================*/


/* jqGrid 封装 */
/*======================================*/

function __init_jqgrid(table_id, page_id, url, colNames, colModel, search, opt) {
    var defaults = {
        url: url,
        loadonce:opt,
        datatype: 'json',
        height: 'auto',
        autowidth:true,
        colNames: colNames,
        colModel: colModel,
        pager: '#'+page_id,
        rowList: [10, 20, 30],
        rowNum: 10,
        rownumbers: true,
        jsonReader: {
            root: 'dataRows',
            repeatitems: false
        },
        prmNames: {
            search:'search'
        },
        gridview: true,
        viewrecords: true,
        viewsortcols: [true, 'vertical', true]
    };
    var options = $.extend({}, defaults, opt);

    $('#'+table_id).jqGrid(options);
    $('#'+table_id).jqGrid('navGrid', '#'+page_id, {
        add: false,
        edit: false,
        del: false,
        search: false
    });
    if (search) {
        $('#'+table_id).jqGrid('filterToolbar', {searchOperators:false, stringResult:true});
    }

}

/*======================================*/

/* validate 封装 */
/*======================================*/

function __init_validate(form_id, opt ,wx) {
    var defaults = {
        ignore: "",
        // 设置错误信息存放标签
        errorElement : 'em',
        // 指定错误信息位置
        errorPlacement : function(error, element) {
            if(wx == 1){
                element.parent().after(error);
            }else{
                if (element.is(':checkbox')) {
                    error.appendTo(element.parent().parent());
                } else {
                    error.appendTo(element.parent());
                }
            }

        }
    };
    var options = $.extend({}, defaults, opt);

    $('#'+form_id).validate(options)
}


/* upload 封装 */
/*======================================*/
/**
 * input页面upload
 * @param opt objId--显示目标位置，entityName--实体名称，sourceId---记录已上传的Id
 */
function inputLoad(opt){
    var defaults={
        objId:null,
        entityName:null,
        sourceId:null,
        jsessionid:null
    };
    var o = $.extend({}, defaults, opt);
    $("#"+ o.objId).upload('init',{entityName: o.entityName});
    var fileId = $("input#"+ o.sourceId).val();
    $("#"+ o.objId).upload('fileList',{
        keyId:fileId,
        entityName: o.entityName,
        del:1
    });
    $("#"+ o.objId).upload('upload',{
        actionUrl: '../common/file/upload;jsessionid='+o.jsessionid,
        entityName: o.entityName,
        multi:true
    });
}
/**
 * read页面upload
 * @param opt objId--显示目标位置，entityName--实体名称，sourceId---记录已上传的Id
 */
function readLoad(opt){
    var defaults={
        objId:null,
        entityName:null,
        sourceId:null
    };
    var o = $.extend({}, defaults, opt);
    var fileId =$("input#"+ o.sourceId).val();
    $("#"+ o.objId).upload('init',{entityName: o.entityName});
    $("#"+ o.objId).upload('fileList',{
        keyId:fileId,
        entityName: o.entityName
    });
}
/**
 * input页面 删除已经upload的文件
 * @param opt id--已经upload的文件的Id
 */
function fn_del_file(id){
    console.debug(id);
    pdata = {keyId:id}
    $.ajax({
        url : "../common/file/delete",
        method:"post",
        cache : false,
        dataType : "json",
        async : false,
        data : pdata,
        success : function(data) {
            var obj = $("li[key='"+id+"']");
            var idObj = $(obj).parent().prev().prev();

            $(idObj).val(idObj.val().replace(id,""));
            $(obj).remove();
            __toastr(data);
        }
    });
}
/**
 * 删除已保存在文档的附件
 * @param id
 */
function del_exist_file(id){
    var obj = $("li[key='"+id+"']");
    var idObj = $(obj).parent().prev().prev();
    $(idObj).val(idObj.val().replace(id,""));
    $(obj).remove();
}
/* url 返回菜单视图 */
/*======================================*/
function returnToHashUrl() {
    var urlHash = window.location.hash;
    var url = urlHash.substring(1,urlHash.length);
    loadURL(url,$('#page-content'));
}

/**
 * 选择身份
 * @param pdata
 */
function doMultiDuty(pdata){
    __open_dialog_select('请选择职权', '../main/getDutyDlg?keyId='+pdata.keyId+"&entityName="+pdata.entityName, function (dialogRef) {
        var callback = function (data) {
            if (data) {
                dialogRef.close();
                var text = "<span id='"+data.id+"'>&nbsp;&nbsp;当前操作人:【"+data.name+"】</span>";
                $("input#curDutyId").focus();
                $("input#curDutyId").val(data.id);
                $(".panel-heading").find('#title').append(text);
            } else {
                dialogRef.enableButtons();
            }
        };
        fn_dialog_multiDuty_select(callback);
    });

}
/**
 * 计算登录人该表单的操作身份
 * @param pdata
 */
function multiDuty(pdata){
    __ajax_get("../main/dutyDlg",pdata,function(pdata){
        if(pdata.data != null && pdata.data.length > 1){
            doMultiDuty(pdata);
        }else{
            if(pdata.data == null){
                __toastr_error("当前操作人没有权限");
                return;
            }
            var data = pdata.data[0];
            if(data){
                var text = "<span id='"+data.id+"'>&nbsp;&nbsp;当前操作人:【"+data.name+"】</span>";
                $("input#curDutyId").focus();
                $("input#curDutyId").val(data.id);
                $(".panel-heading").find('#title').append(text);
            }else{
                __toastr_error("当前操作人没有权限");
            }
        }
    });
}

// 部门选择框
function fn_departments_dialog_select(isMulti,nameField,idField) {

    __open_dialog_select('选择部门', '../main/department/dialog?multi='+isMulti+'&deptIds='+ $('#'+idField).val(), function (dialogRef) {
        var callback = function (data) {
            if (data) {
                dialogRef.close();
                $('#'+idField).val(data.ids);
                $('#'+nameField).val(data.names);
            } else {
                dialogRef.enableButtons();
            }
        };
        fn_dialog_departments_select(callback);
    });
}

//用户选择框
function fn_members_dialog_select(nameField,idField) {

    __open_dialog_select('选择成员', '../main/member/dialogs?sids='+$("#"+idField).val(), function (dialogRef) {
        var callback = function (data) {
            if (data) {
                dialogRef.close();
                $('#'+idField).val(data.ids);
                $('#'+nameField).val(data.names);
            } else {
                dialogRef.enableButtons();
            }
        };
        fn_dialog_members_select(callback);
    });
}
